<?php

namespace App\Http\Requests;

use App\Models\Address;
use App\Models\Goods;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class OrdersAdd extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'address_id' => [
                'required', function($attribute, $value, $fail) {
                    if (!$value) {
                        $fail('收货地址错误');
                        return;
                    }
                    $count = Address::whereUserId(auth('wechat')->id())
                        ->where('id', $value)
                        ->count();
                    if ($count == 0) {
                        $fail('收货地址错误!!!');
                        return;
                    }
                }
            ],
            'goods_info' => [
                'required', function($attribute, $value, $fail) {
                    if (!is_array($value)) {
                        $fail('购买信息错误');
                        return;
                    }
                    try {
                        foreach ($value as $item) {
                            if ($item['goods_id'] < 1) {
                                $fail('商品购买id错误');
                                return;
                            }
                            if ($item['buy_count'] < 1) {
                                $fail('商品购买数量不能小于1');
                                return;
                            }
                            $stock_num = Goods::whereId($item['goods_id'])->value('stock_num');
                            if ($item['buy_count'] > $stock_num) {
                                $fail('商品购买数量不能大于库存');
                                return;
                            }
                        }
                    } catch (\Exception $exception) {
                        \Log::error($exception);
                        $fail('购买信息字段错误');
                        return;
                    }
                }
            ],
        ];
    }

    public function messages()
    {
        return [
            'address_id.required' => '请选择收货地址',
            'goods_info.required' => '请选择购买的商品',
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            "code"  => 500,
            "msg"   => $validator->getMessageBag()->first(),
            "data"  => null,
        ], 200, [
            'Content-Type'=>'application/json; charset=UTF-8'
        ]));
    }
}
